/*
 * TestG722.cpp
 *
 *  Created on: 2017年8月20日
 *      Author: terry
 */

#include "TestG722.h"
#include "G722Transcoder.h"
#include "MediaPacket.h"
#include "TFileUtil.h"
#include "TByteBuffer.h"
#include "CLog.h"


using namespace av;


TestG722::TestG722()
{
	av::AudioFormat g722Format;
	g722Format.m_codec = MEDIA_CODEC_G722;
	g722Format.m_channels = 1;
	g722Format.m_samplerate = 16000;

	av::AudioFormat g711Format;
	g711Format.m_codec = MEDIA_CODEC_G711A;
	g711Format.m_channels = 1;
	g711Format.m_samplerate = 8000;

	m_g722Encoder.open(g711Format, g722Format);
	m_g722Decoder.open(g722Format, g711Format);
}

TestG722::~TestG722()
{
}

void TestG722::testDecodeG722()
{
	HKG722Decoder decoder;
	decoder.open();

	FILE* file = NULL;
	fopen_s(&file, "d:\\hkgate\\bin\\from_hk.g722", "rb");
	if (file)
	{
		unsigned char buffer[HKG722Decoder::PACKET_SIZE];
		comn::ByteBuffer	outBuffer;
		outBuffer.ensure(HKG722Decoder::PCM_SIZE * 2);

		while (!feof(file))
		{
			size_t length = fread(buffer, 1, HKG722Decoder::PACKET_SIZE, file);
			if (length != HKG722Decoder::PACKET_SIZE)
			{
				break;
			}

			int count = decoder.decode(buffer, length, outBuffer.data());

			if (count > 0)
			{
				comn::FileUtil::write(outBuffer.data(), count, "out.pcma", true);
			}
		}

		fclose(file);
	}

	decoder.close();
}

void TestG722::test()
{
	FILE* file = NULL;
	fopen_s(&file, "g:\\hk\\dump_from_hk.g722", "rb");
	if (file)
	{
		unsigned char buffer[HKG722Decoder::PACKET_SIZE * 2];

		comn::ByteBuffer	outBuffer;
		outBuffer.ensure(HKG722Decoder::PCM_SIZE * 4);

		while (!feof(file))
		{
			size_t toRead = HKG722Decoder::PACKET_SIZE * 2;
			size_t length = fread(buffer, 1, toRead, file);
			if (length != toRead)
			{
				break;
			}

			onData(buffer, length);
		}

		fclose(file);
	}
}

void TestG722::onData(uint8_t* data, int size)
{
	AVPacket pkt;
	av_init_packet(&pkt);
	pkt.data = (unsigned char*)data;
	pkt.size = size;

	MediaPacketPtr outPkt(new MediaPacket());
	outPkt->set_type(MEDIA_TYPE_AUDIO);
	if (!m_g722Decoder.transcode(&pkt, outPkt->get()))
	{
		CLog::warning("failed to transcode to g711.\n");
		return;
	}

	if (true)
	{
		comn::FileUtil::write(outPkt->data(), outPkt->size(), "dump_from_hk.pcm", true);
	}

	onPcmData(outPkt);
}

void TestG722::onPcmData(av::MediaPacketPtr& pkt)
{
	MediaPacketPtr outPkt(new MediaPacket());
	outPkt->set_type(MEDIA_TYPE_AUDIO);
	if (m_g722Encoder.transcode(pkt->get(), outPkt->get()))
	{
		if (true)
		{
			comn::FileUtil::write(outPkt->data(), outPkt->size(), "dump_to_hk.g722", true);
		}

	}
}